<template>
  <div>
    <el-button type="danger" @click="batchDelete()">批量删除</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      @node-click="handleNodeClick"
      :expand-on-click-node="false"
      :default-expanded-keys="expandKey"
      show-checkbox
      node-key="catId"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            type="text"
            v-if="data.catLevel <= 2"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            edit
          </el-button>
          <el-button
            type="text"
            size="mini"
            v-if="data.children.length == 0"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="统一单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="suitDialogType()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "",
      dialogVisible: false,
      dialogType: "",
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: "",
        productUnit: "",
      },
      menus: [],
      expandKey: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  methods: {
    batchDelete() {
      //得到所有选中的category
      let catArray = [];
      catArray = this.$refs.tree.getCheckedNodes();
      let ids = [];
      let names=[];
      for (let i = 0; i < catArray.length; i++) {
        ids.push(catArray[i].catId);
        names.push(catArray[i].name);
      }

      //发送删除请求
      this.$confirm(`确定要删除【${names}】菜单么？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(
              ids,
              false
            ),
          })
            .then(() => {
              //刷新界面
              this.getCategroyData();
              this.$message({
                message: "批量删除菜单成功",
                type: "success",
              });
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    handleNodeClick(data) {
      console.log(data);
    },
    getCategroyData() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("成功得到數據", data);

        this.menus = data.data;
      });
    },
    edit(data) {
      //弹出对话框
      this.dialogVisible = true;
      //和添加作区分
      this.dialogType = "edit";
      this.title = "修改分类";
      //初始化数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        console.log("成功得到数据", data);
        this.category.catId = data.data.catId;
        this.category.name = data.data.name;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid;
      });
    },
    suitDialogType() {
      if (this.dialogType == "edit") {
        this.editCategory();
      } else if (this.dialogType == "append") {
        this.addCategory();
      }
    },
    append(data) {
      //设置类型
      this.dialogType = "append";
      this.title = "添加分类";
      //弹出对话框
      this.dialogVisible = true;
      //初始化category数据
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.catId = null;
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.name = "";
      this.category.sort = 0;
    },
    editCategory() {
      //不能直接传category，因为一些默认的数据会覆盖原来的category
      let { catId, name, icon, productUnit } = this.category;
      //添加category
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      })
        .then(() => {
          //刷新界面
          this.getCategroyData();

          //设置默认展开的id(被删除结点的父id)
          this.expandKey = [this.category.parentCid];
          this.$message({
            message: "菜单修改成功",
            type: "success",
          });
          //关闭对话框
          this.dialogVisible = false;
        })
        .catch(() => {});
    },
    addCategory() {
      //添加category
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      })
        .then(() => {
          //刷新界面
          this.getCategroyData();

          //设置默认展开的id(被删除结点的父id)
          this.expandKey = [this.category.parentCid];
          this.$message({
            message: "菜单添加成功",
            type: "success",
          });
          //关闭对话框
          this.dialogVisible = false;
        })
        .catch(() => {});
    },

    remove(node, data) {
      let ids = [data.catId];
      //删除之前应该有提示，删除之后也要提示
      this.$confirm(`确定要删除【${data.name}】菜单么？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //删除数据
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(() => {
            console.log("删除成功");
            //刷新界面
            this.getCategroyData();

            //设置默认展开的id(被删除结点的父id)
            this.expandKey = [data.parentCid];
            this.$message({
              message: "菜单删除成功",
              type: "success",
            });
          });
        })
        .catch(() => {});
    },
  },
  created() {
    this.getCategroyData();
  },
};
</script>

<style>
</style>